<?php
namespace app\controller\toolkit;

use app\exception\ErrnoPlus;
use share\service\cache\CommonCacheKeyService;
use share\controller\ApiBaseController;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\RedisService;
use share\utils\Helper;
use think\response\Json;

class ToolkitApiController extends ApiBaseController{

    CONST LOGIN_TOKEN_TIMEOUT = 3600;

    protected $beforeActionList = [
        "checkUser",
        "checkSign",
    ];

    protected $_userInfo = null;

    /**
     * @param array $data
     * @return \think\response\Json
     */
    public static function json_out($data,$isLog = true){         
        return new Json($data);
    }

    /**
     * @return \think\response\Json
     */
    public static function ok($data = [],$msg = 'success',$code = 0){
        $resp = [
            'resultCode' => $code ,
            'errorString' => $msg,
        ];
        if($data){
            $resp['body'] = $data;
        }
        return self::json_out($resp);
    }

    /**
     * @return \think\response\Json
     */
    public static function fail( $msg, $code = Errno::COMMON_UNKNOWN, $data = []){
        $resp = [
            'resultCode' => $code,
            'errorString' => $msg,
        ];
        if($data){
            $resp['body'] = $data;
        }
        return self::json_out($resp);
    } 


    public static function authToken($userInfo){
        $token = Helper::getUnique();
        $key = self::getAuthCacheKey($token);
        RedisService::instance(RedisService::CACHE_DB_BASE)->setJson($key,$userInfo,self::LOGIN_TOKEN_TIMEOUT);
        return $token;
    }

    public static function getAuthInfoByToken($token){
        $key = self::getAuthCacheKey($token);
        return RedisService::instance(RedisService::CACHE_DB_BASE)->getJson($key);
    }

    public static function getAuthCacheKey($token){
        return CommonCacheKeyService::getCacheKey(CommonCacheKeyService::CACHE_KEY_LOGIN_TOOLKIT ,['token' =>md5($token)]);
    }


    /**
     * 检查已登录用户
     */
    public function checkUser(){
      
        $token = $this->request->header('token');      
        if(empty($token)){
            throw new ApiException("当前用户未登录",ErrnoPlus::WEB_LOGOUT);
        }   
        $userInfo = self::getAuthInfoByToken($token);
        if(empty($userInfo)){
            throw new ApiException("当前用户登录信息已过期,请重新登录",ErrnoPlus::WEB_LOGOUT);
        }
        $this->_userInfo = $userInfo;
        $cacheKey = self::getAuthCacheKey($token);
        return RedisService::instance(RedisService::CACHE_DB_BASE)->expire($cacheKey,self::LOGIN_TOKEN_TIMEOUT);
       
    }
}